<?php
/**
 * Created by PhpStorm.
 * User: Joshua Conero
 * Date: 2019/9/6
 * Time: 22:17
 * Email: conero@163.com
 */

namespace app\api\controller;
use app\common\controller\Api;
use app\common\utils\EnumBase;
use hyang\Util;

class RefAccount extends Api
{
    const RefAccountFiles = 'runtime/ref-account-files';

    /**
     * 文件上传
     * @return \think\response\Json
     */
    function csv_upload(){
        $data = [
            'code' => EnumBase::FeekFailureCode,
            'msg'  => '无效的请求'
        ];
        $filepond = $_FILES['filepond'] ?? null;
        if($filepond){
            $name = ROOT_PATH . self::RefAccountFiles;
            if (!is_dir($name)) mkdir($name, '0777', true);
            $hash = sha1($filepond['name'] . time(). Util::randStr(6));

            $name .= '/'.$hash . '.csv';
            move_uploaded_file($filepond['tmp_name'], $name);

            $data['code'] = EnumBase::FeekSuccessCode;
            $data['msg']  = '文件上传成功';
            $data['hash'] = $hash;
        }
        return $this->FeekMsg($data);
    }

    /**
     * csv 导入
     */
    function csv(){
        $req = $this->request;
        $ref_type = $req->post('ref_type');
        $file_hash = $req->post('file_hash');
        $fileName = ROOT_PATH. self::RefAccountFiles. '/'.($file_hash ?? ''). '.csv';
        $data = ['code' => EnumBase::FeekFailureCode, 'msg' => ''];
        if(empty($ref_type) || empty($file_hash)){
            if(is_file($fileName)) unlink($fileName);
            $data['msg'] = '请求参数无效！';
        }elseif (!is_file($fileName)){
            $data['msg'] = '上传的文件错误！';
        }else{
            //@TODO 实现参照表写入
            //csv 读取
            // ACOUNT.MARK.ROWORDER-LINEID      行列表数据
            // ACOUNT.MARK.KVS-LINEID           kv标志
            $lineMarkId = '';
            $row = 1;
            if (($handle = fopen($fileName, "r")) !== FALSE) {
                while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                    $num = count($data);
                    echo "<p> $num fields in line $row: <br /></p>\n";
                    $row++;
                    for ($c=0; $c < $num; $c++) {
                        echo $data[$c] . "<br />\n";
                    }
                }
                fclose($handle);
            }
        }

        return $this->FeekMsg($data);
    }
}